package com.example.bluetoothclicker.home

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.DialogInterface
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import com.example.bluetoothclicker.R
import com.example.bluetoothclicker.func.BluetoothConnectionManager
import com.example.bluetoothframework.connection.ConnectionModule
import com.example.bluetoothframework.connection.ConnectionState
import com.example.bluetoothframework.connection.PairingState
import com.example.bluetoothframework.scan.ScanModule

class BluetoothDeviceDialogFragment : DialogFragment() {

    private lateinit var pairedDeviceListView: ListView
    private lateinit var scannedDeviceListView: ListView
    private lateinit var progressBar: ProgressBar
    private lateinit var scanButton: Button
    private lateinit var stopScanButton: Button
    private lateinit var closeButton: ImageButton

    private lateinit var scanModule: ScanModule
    private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
    private val pairedDevicesAdapter: ArrayAdapter<String> by lazy {
        ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, mutableListOf<String>())
    }
    private val scannedDevicesAdapter: ArrayAdapter<String> by lazy {
        ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, mutableListOf<String>())
    }
    private val scannedDevices = mutableMapOf<String, BluetoothDevice>()
    private val handler = Handler(Looper.getMainLooper())
    private var isAutoScanning = false // 自动扫描标记
    private var isInterval = false // 是否处于间隔期

    override fun onResume() {
        super.onResume()
        dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.dialog_bluetooth_devices, container, false)

        pairedDeviceListView = view.findViewById(R.id.pairedDeviceListView)
        scannedDeviceListView = view.findViewById(R.id.scannedDeviceListView)
        progressBar = view.findViewById(R.id.progressBar)
        scanButton = view.findViewById(R.id.scanButton)
        stopScanButton = view.findViewById(R.id.stopScanButton)
        closeButton = view.findViewById(R.id.closeButton)

        pairedDeviceListView.adapter = pairedDevicesAdapter
        scannedDeviceListView.adapter = scannedDevicesAdapter

        scanModule = ScanModule(requireContext())
        loadPairedDevices()

        // 观察扫描到的设备
        scanModule.scannedDevices.observe(viewLifecycleOwner) { scannedDevicesList ->
            // 清空旧数据
            scannedDevices.clear()
            scannedDevicesAdapter.clear()

            // 遍历新的扫描结果
            scannedDevicesList.forEach { scannedDevice ->
                // 构建设备信息字符串
                val deviceInfo = "${scannedDevice.name ?: "未知设备"} (${scannedDevice.type.name})\n${scannedDevice.address}"

                // 更新 scannedDevices
                val bluetoothDevice = bluetoothAdapter?.getRemoteDevice(scannedDevice.address)
                if (bluetoothDevice != null) {
                    scannedDevices[deviceInfo] = bluetoothDevice
                    // 更新 scannedDevicesAdapter
                    scannedDevicesAdapter.add(deviceInfo)
                }
            }

            // 通知适配器数据已改变
            scannedDevicesAdapter.notifyDataSetChanged()
        }



        scanButton.setOnClickListener { startScanImmediately() }
        stopScanButton.setOnClickListener { stopAutoScanning() }
        closeButton.setOnClickListener { dismiss() }

        pairedDeviceListView.setOnItemClickListener { _, _, position, _ ->
            val selectedInfo = pairedDevicesAdapter.getItem(position)
            val selectedDevice = bluetoothAdapter?.bondedDevices?.find {
                selectedInfo?.contains(it.address) == true
            }

            selectedDevice?.let { onDeviceSelected(it) }?: showToast("设备信息无效")
        }

        // 点击事件监听器
        scannedDeviceListView.setOnItemClickListener { _, _, position, _ ->
            // 获取选中的设备信息
            val selectedInfo = scannedDevicesAdapter.getItem(position)

            // 从 scannedDevices 中找到对应的 BluetoothDevice 对象
            val selectedDevice = scannedDevices[selectedInfo]

            // 调用 onDeviceSelected 方法处理设备选择
            selectedDevice?.let { onDeviceSelected(it) } ?: showToast("设备信息无效")
        }




        startScanWithAuto()

        return view
    }

    private fun loadPairedDevices() {
        pairedDevicesAdapter.clear()
        bluetoothAdapter?.bondedDevices?.forEach { device ->
            val info = "设备名: ${device.name ?: "未知"}\n地址: ${device.address}"
            pairedDevicesAdapter.add(info)
        }
    }


    /**
     * 将配对成功的设备移到已配对设备列表
     */
    private fun moveDeviceToPairedList() {
        val bondedDevices = bluetoothAdapter?.bondedDevices ?: return
        bondedDevices.forEach { bondedDevice ->
            val deviceInfo = "设备名: ${bondedDevice.name ?: "未知"}\n地址: ${bondedDevice.address}"

            // 如果扫描列表中有此设备，移除
            if (scannedDevices.containsKey(deviceInfo)) {
                scannedDevices.remove(deviceInfo)
                scannedDevicesAdapter.remove(deviceInfo)
                scannedDevicesAdapter.notifyDataSetChanged()
            }

            // 添加到配对设备列表，如果尚未存在
            if (!isDeviceInAdapter(pairedDevicesAdapter, deviceInfo)) {
                pairedDevicesAdapter.add(deviceInfo)
                pairedDevicesAdapter.notifyDataSetChanged()
            }
        }
    }

    /**
     * 检查设备信息是否已在 ArrayAdapter 中
     */
    private fun isDeviceInAdapter(adapter: ArrayAdapter<String>, deviceInfo: String): Boolean {
        for (i in 0 until adapter.count) {
            if (adapter.getItem(i) == deviceInfo) return true
        }
        return false
    }


    /**
     * 处理设备点击事件
     */
    private fun onDeviceSelected(device: BluetoothDevice) {
        if (BluetoothConnectionManager.isConnectedAsServe()||BluetoothConnectionManager.isConnectedAsClient()) {
            // 当前已有活跃的连接，询问用户是否断开连接
            showConfirmDialog(
                title = "设备已连接",
                message = "您已连接到其他设备，是否断开连接并连接到新的设备？",
                onConfirm = {
                    // 用户确认断开当前连接
                    BluetoothConnectionManager.closeAllCollected()
                    connectToNewDevice(device)
                },
                onCancel = {
                    // 用户取消操作
                    showToast("连接已取消")
                }
            )
        } else {
            // 没有活跃连接，直接连接到新设备
            connectToNewDevice(device)
        }
    }
    private fun showConfirmDialog(
        title: String,
        message: String,
        onConfirm: () -> Unit,
        onCancel: () -> Unit
    ) {
        AlertDialog.Builder(requireContext())
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton("确认") { _, _ -> onConfirm() }
            .setNegativeButton("取消") { _, _ -> onCancel() }
            .show()
    }


    private fun connectToNewDevice(device: BluetoothDevice) {
        showToast("正在连接到设备: ${device.name ?: "未知设备"}")
        BluetoothConnectionManager.connectToServer(
            device = device,
            onConnected = { message ->
                Handler(Looper.getMainLooper()).post { showToast(message) }
            },
            onError = { error ->
                Handler(Looper.getMainLooper()).post { showToast(error) }
            }
        )
    }

    /**
     * 显示 Toast 提示
     */
    private fun showToast(message: String) {
        if (this.context == null) return
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
    }

    /**
     * 开始扫描并启动自动扫描流程
     */
    private fun startScanWithAuto() {
        if (isAutoScanning) return
        isAutoScanning = true
        startScan()
    }

    /**
     * 立即触发扫描
     */
    private fun startScanImmediately() {
        if (isInterval){
            // 中止当前的间隔计时
            handler.removeCallbacksAndMessages(null)
            // 立刻开始扫描
            startScan()
        }
        if (!isAutoScanning){
            startScanWithAuto()
        }

    }

    /**
     * 启动扫描任务
     */
    private fun startScan() {
        isInterval = false // 切换状态为扫描中
        progressBar.visibility = View.VISIBLE
        scanButton.isEnabled = false
        stopScanButton.isEnabled = true
        scanModule.startScan(scanDuration = 10000L) // 每次扫描持续 10 秒

        // 扫描完成后进入间隔计时
        handler.postDelayed({
            progressBar.visibility = View.GONE
            scanButton.isEnabled = true
            stopScanButton.isEnabled = true
            if (isAutoScanning) scheduleNextScan() // 进入间隔阶段
        }, 10000L)
    }

    /**
     * 安排下一次扫描任务
     */
    private fun scheduleNextScan() {
        isInterval = true // 切换状态为间隔期
        handler.postDelayed({
            if (isAutoScanning) startScan() // 再次启动扫描
        }, 20000L)
    }

    /**
     * 停止扫描
     */
    private fun stopScan() {
        progressBar.visibility = View.GONE
        scanButton.isEnabled = true
        stopScanButton.isEnabled = false
        scanModule.stopScan()
    }

    /**
     * 停止自动扫描流程
     */
    private fun stopAutoScanning() {
        isAutoScanning = false
        isInterval = false
        handler.removeCallbacksAndMessages(null) // 移除所有延迟任务
        stopScan() // 停止当前扫描
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        stopAutoScanning() // 退出时停止自动扫描
    }
}
